package com.login_php.manager;

import java.io.InputStream;
import java.security.Key;
import java.util.ResourceBundle;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;

import com.login_php.services.UsuarioService;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SecurityEng {

	private static final String ENCRIPTION_KEY = "first.key";
	private static final String BUNDLE = "security";
	private static final String ALGO = "AES";
	private static final String CRIPTO_KEY;
	
	static{
		CRIPTO_KEY = ResourceBundle.getBundle(BUNDLE).getString(ENCRIPTION_KEY);
	}

	public static String encrypt(String Data) throws Exception {
		
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGO);
		c.init(Cipher.ENCRYPT_MODE, key);
		byte[] encVal = c.doFinal(Data.getBytes());
		String encryptedValue = new BASE64Encoder().encode(encVal);
		return encryptedValue;
	}

	public static String decrypt(String encryptedData) throws Exception {
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGO);
		c.init(Cipher.DECRYPT_MODE, key);
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
		byte[] decValue = c.doFinal(decordedValue);
		String decryptedValue = new String(decValue);
		return decryptedValue;
	}

	private static Key generateKey() throws Exception {

		Key key = new SecretKeySpec(CRIPTO_KEY.getBytes(), ALGO);
		return key;
	}
}